import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_module/eventbus_mgr.dart';

//MethodChannel
const _methodChannel = const MethodChannel('com.example/method_channel');

class MyMethodChannel {
 /*
 * flutter调用native
 * 示例：
 * var result = await MyMethodChannel.callNative("methodTest", {"param":"params from flutter"});
 */
  static Future<Map> callNative(String methodName, [Map? params]) async {
    var result;
    try {
      if (params == null) {
        result = await _methodChannel.invokeMethod('$methodName');
      } else {
        result = await _methodChannel.invokeMethod('$methodName', params);
      }
    } catch (e) {
      result = {'Failed': e.toString()};
    }
    print("callNative result:${result.toString()}");
    return json.decode(result);
  }

  /**
   * native调用flutter
   */
  static void registerCallFromNative() {
    _methodChannel.setMethodCallHandler((call) async {
      print("methodHandlerListener call:${call.toString()}");
      switch (call.method) {
        case 'setInitRoute':
          RouteEvent myUser = RouteEvent(call.arguments);
          eventBus.fire(myUser);
          break;

        case "methodToFlutter":
          print("methodToFlutter arg:${call.arguments}");
          await Future.delayed(const Duration(seconds: 7));
          return "delayed 7 seconds";
        case "keyEvent":
          print("keyEvent arg:${call.arguments}");
          break;
        default:
          return "not implemented";
      }
    });
  }


}
